<template>
  <div class="demo">
    <h1>用户管理</h1>
    <!-- 搜索区域 -->
    <div class="search-container">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="用户名">
          <el-input v-model="searchForm.userName" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="searchForm.role" placeholder="请选择角色">
            <el-option label="管理员" value="0"></el-option>
            <el-option label="教师" value="1"></el-option>
            <el-option label="学生" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button type="info" @click="resetSearch">重置</el-button>
          <el-button type="success" @click="handleAdd" >新增用户</el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <div class="main-content">
    <!--表格数据展示 -->
    <el-table
        :data="tableData"
        border
        v-loading="loading"
        style="width: 100%"
        height="calc(100vh - 250px)"
        :header-cell-style="{background:'#f5f7fa',color:'#606266'}"
    >
      <el-table-column
          label="ID"
          prop="id"
          width="60">
      </el-table-column>
      <el-table-column
          label="用户名"
          prop="userName"
          min-width="120"
          :show-overflow-tooltip="true">
      </el-table-column>
      <el-table-column
          label="角色"
          prop="role"
          width="80">
        <template slot-scope="{row}">
          {{ roleMap[row.role] }}
        </template>
      </el-table-column>
      <el-table-column
          label="创建时间"
          prop="createTime"
          min-width="150"
          :show-overflow-tooltip="true">
      </el-table-column>
      <el-table-column
          label="操作"
          width="160"
          fixed="right"
          v-if="role === 0">
        <template slot-scope="scope">
            <div class="operation-buttons">
          <el-button type="primary" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" @click="handleDelete(scope.row)">删除</el-button>
            </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控件 -->
    <div class="pagination-container">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
      </div>
    </div>

    <!-- 新增/编辑用户对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="30%">
      <el-form :model="form" :rules="rules" ref="userForm" label-width="100px">
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="form.userName"  placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" show-password placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="form.role" placeholder="请选择角色">
            <el-option label="管理员" value="0"></el-option>
            <el-option label="教师" value="1"></el-option>
            <el-option label="学生" value="2"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
/* eslint-disable no-unused-vars */
export default {
  name: "UserDemo",
  data() {
    return {
      tableData: [],
      loading: false,
      form: {
        id: '', // 新增 id 字段用于编辑时传递
        userName: '',
        password: '',
        role: '',
      },
      //分页参数
      pageSize: 10,
      pageNum: 1,
      total: 0,
      // 搜索表单
      searchForm: {
        userName: '',
        role: ''
      },
      // 控制对话框显示
      dialogVisible: false,
      // 对话框标题
      dialogTitle: '',
      // 对话框类型（新增或编辑）
      dialogType: '',
      // 表单验证规则
      rules: {
        userName: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { validator: this.validateUserNameUnique, trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
        ],
        role: [
          { required: true, message: "请选择角色", trigger: "change" },
        ],
      },
      originalUserName: '',
      roleMap: {
        0: '管理员',
        1: '教师',
        2: '学生'
      }
    }
  },
  computed: {
    role() {
      return this.getRole();
    }
  },
  methods: {
    getRole() {
      const user = JSON.parse(localStorage.getItem('currentUser'));
      return user ? user.role : '';
    },
    validateUserNameUnique(rule, value, callback) {
      // 如果没有输入用户名，不进行校验
      if (!value) {
        callback();
        return;
      }

      // 如果是编辑模式且用户名没有改变，不进行校验
      if (this.dialogType === "edit" && this.originalUserName === value) {
        callback();
        return;
      }

      // 调用后端接口检查用户名是否存在
      this.$http
          .get("/user/checkUserName", {
            params: { userName: value }
          })
          .then((res) => {
            if (res.data && res.data.code === 200) {
              // 如果用户名不存在，校验通过
              if (!res.data.data) {
                callback();
              } else {
                // 如果用户名已存在，校验失败
                callback(new Error("该用户名已被使用，请更换"));
              }
            } else {
              // 接口调用失败
              callback(new Error("用户名验证失败，请稍后再试"));
            }
          })
          .catch(() => {
            callback(new Error("网络请求失败，请检查网络连接"));
          });
    },
    loadData() {
      this.loading = true;
      this.$http.post('/user/listPage', {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        param: {
          userName: this.searchForm.userName,
          role: this.searchForm.role
        }
      }).then(res => res.data)
          .then(res => {
        this.loading = false;
        if (res.code == 200) {
          this.tableData = res.data;
          console.log("tableData:", this.tableData)
          this.total = res.total;
        } else {
          this.$message.error('获取数据失败: ' + res.msg);
        }
      }).catch(err => {
        this.loading = false;
        console.error("请求错误:", err);
        this.$message.error("网络请求失败，请检查网络连接");
      });
    },
    //处理每页条数变化
    handleSizeChange(val) {
      this.pageSize = val;
      this.loadData();
    },
    // 处理当前页变化
    handleCurrentChange(val) {
      this.pageNum = val;
      this.loadData();
    },
    // 处理查询
    handleSearch() {
      this.pageNum = 1;
      this.loadData();
    },
    // 重置查询条件
    resetSearch() {
      this.searchForm = {
        userName: '',
        role: ''
      };
      this.handleSearch();
    },
    // 打开新增对话框
    handleAdd() {
      this.dialogType = 'add';
      this.dialogTitle = '新增用户';
      this.openDialog();
    },
    // 打开对话框通用方法
    openDialog(row) {
      this.dialogVisible = true;
      
      this.$nextTick(() => {
        if (this.$refs.userForm) {
          this.$refs.userForm.resetFields();
        }
        
        if (row) {
          // 编辑模式：填充表单数据
          this.originalUserName = row.userName; // 记录原始用户名
          
          this.form = {
            id: row.id,
            userName: row.userName,
            password: row.password,
            role: row.role.toString()
          };
        } else {
          // 新增模式：设置默认值
          this.originalUserName = ''; // 清空原始用户名
          this.form = {
            id: '',
            userName: '',
            password: '',
            role: ''
          };
        }
      });
    },
    // 提交表单
    submitForm() {
      this.$refs.userForm.validate((valid) => {
        if (valid) {
          if (this.dialogType === "add") {
            this.confirmAdd();
          } else if (this.dialogType === "edit") {
            this.confirmEdit();
          }
        } else {
          return false;
        }
      });
    },
    // 确认新增
    confirmAdd() {
      this.$http.post('/user/create', {
        userName: this.form.userName,
        password: this.form.password,
        role: this.form.role
      }).then(res => res.data).then(res => {
        if (res.code == 200) {
          this.$message.success('新增成功');
          this.dialogVisible = false;
          this.loadData();
        } else {
          this.$message.error('新增失败: ' + res.msg);
        }
      }).catch(err => {
        console.error("添加请求错误:", err);
        this.$message.error("网络请求失败，请稍后重试");
      });
    },
    // 编辑操作
    handleEdit(row) {
      this.dialogType = 'edit';
      this.dialogTitle = '编辑用户';
      this.openDialog(row);
    },
    // 确认编辑
    confirmEdit() {
      this.$http.post('/user/update', {
        id: this.form.id,
        userName: this.form.userName,
        password: this.form.password,
        role: this.form.role
      }).then(res => res.data).then(res => {
        if (res.code == 200) {
          this.$message.success('编辑成功');
          this.dialogVisible = false;
          this.loadData();
        } else {
          this.$message.error('编辑失败: ' + res.msg);
        }
      }).catch(err => {
        console.error("更新请求错误:", err);
        this.$message.error("网络请求失败，请稍后重试");
      });
    },
    //  删除操作
    handleDelete(row) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.delete('/user/delete/' + row.id)
          .then(res => res.data)
          .then(res => {
          if (res.code == 200) {
            this.$message.success('删除成功');
            this.loadData();
          } else {
            this.$message.error('删除失败: ' + res.msg);
          }
        }).catch(error => {
          console.error('删除请求失败:', error);
          this.$message.error('删除请求失败，请稍后重试');
        });
      }).catch(() => {
        // 用户点击取消时的处理逻辑
        this.$message.info('已取消删除');
      });
    }
  },
  created() {
    this.loadData();
  }
}
</script>

<style scoped>
.demo {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.search-container {
  margin-bottom: 15px;
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
}

.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.el-table {
  flex: 1;
  overflow: hidden;
}

.pagination-container {
  margin-top: 15px;
  text-align: right;
}

.operation-buttons {
  display: flex;
  justify-content: space-between;
}

.operation-buttons .el-button {
  margin-left: 0;
  margin-right: 5px;
  padding: 5px 8px;
}

::v-deep .el-table .cell {
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}
</style>